package com.mingweicai.intergration.thread;

import java.util.concurrent.Semaphore;

public class SemaphoreTest {

  public static void main(String args[]){

    // 只能同时有两个人坐座位
    Semaphore semaphore = new Semaphore(2);

    Runnable runnable = new SemaphoreRunnable(semaphore);
    Thread threadA = new Thread(runnable);
    threadA.setName("A");
    threadA.start();

    Thread threadB = new Thread(runnable);
    threadB.setName("B");
    threadB.start();

    Thread threadC = new Thread(runnable);
    threadC.setName("C");
    threadC.start();

    Thread threadD = new Thread(runnable);
    threadD.setName("D");
    threadD.start();

  }

  static class SemaphoreRunnable implements Runnable{

    private Semaphore semaphore;
    public SemaphoreRunnable(Semaphore semaphore) {
      this.semaphore = semaphore;
    }

    @Override
    public void run() {
      try {
        semaphore.acquire();
        System.out.println("Thread " + Thread.currentThread().getName() +" 获取到了座位许可");
        System.out.println("Thread " + Thread.currentThread().getName() +"正在处理....");
        Thread.sleep(2000);
        System.out.println("Thread " + Thread.currentThread().getName() +"处理完成....");
        semaphore.release();
        System.out.println("Thread " + Thread.currentThread().getName() +" 释放了座位许可");

      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
}
